package edu.scu.declaresys.web.action;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ModelDriven;

import edu.scu.declaresys.config.IAttrName;
import edu.scu.declaresys.service.ServiceFactory;
import edu.scu.declaresys.service.intr.INewsClassService;
import edu.scu.declaresys.vo.NewsClass;
import edu.scu.declaresys.web.ABaseAction;

/**
 * 
 * @author: zt
 * @since : 2013-7-12
 */
public class NewsClassAction extends ABaseAction implements ModelDriven<NewsClass>
{
	private static final long	serialVersionUID	= 331796124737938073L;
	
	private INewsClassService service = ServiceFactory.createNewsClassService();
	
	private NewsClass vo = new NewsClass();
	
	//
	// actoin
	//
	public String newsClassAdd() throws Exception
	{
		if(vo.getName() == null)
		{
			throw new Exception("类别名称不能为空");
		}
		if(service.findClassByName(vo.getName()) != null)
		{
			throw new Exception("类别已经存在");
		}
		vo.setId(service.addClass(vo));
		request.setAttribute(IAttrName.CLASS_VO, vo);
		return Action.SUCCESS;
	}
	
	public String newsClassDelete() throws Exception
	{
		if(vo.getId() == null)
		{
			throw new Exception("未指定ID");
		}
		else
		{
			if(ServiceFactory.createNewsService().findNewsList(vo.getId(), null).isEmpty())
			{
				service.deleteClass(vo.getId());
			}
			else
			{
				throw new Exception("该类别下还有内容，不能删除！");
			}				
		}
		return Action.SUCCESS;
	}
	
	public String newsClassModify() throws Exception
	{
		if(vo.getName() != null)
		{
			if(vo.getId() == null)
			{
				throw new Exception("未指定类别或类类别名未填");
			}
			else if(service.findClassByName(vo.getName()) != null)
			{
				throw new Exception("该类别已经存在！");
			}
			else if(service.findClass(vo.getId()) == null)
			{
				throw new Exception("该类别不存在");
			}
			service.modifyClass(vo);
		}
		return Action.SUCCESS;
	}
	
	public String newsClassList() throws Exception
	{
		request.setAttribute(IAttrName.CLASS_LIST, service.findClassList());
		return Action.SUCCESS;
	}
	
	public String newsClassDetail() throws Exception
	{
		if(vo.getId() != null)
		{
			throw new Exception("未指定类别！");
		}
		vo = service.findClass(vo.getId());
		request.setAttribute(IAttrName.CLASS_VO, vo);
		return Action.SUCCESS;
	}
	
	public String newsClassCheckDuplicate() throws Exception
	{
		boolean isDuplicate = (service.findClassByName(vo.getName()) != null);
		request.setAttribute(IAttrName.CLASS_DUPLICATE_FLAG, isDuplicate);
		return Action.SUCCESS;
	}

	
	//
	// Getters and Setters.
	//
	
	@Override
	public NewsClass getModel()
	{
		return vo;
	}

	public NewsClass getNewsClass()
	{
		return vo;
	}

	public void setNewsClass(NewsClass newsClass)
	{
		this.vo = newsClass;
	}
}
